<template>
  <div >
    <div v-show="show_tags">
      <i-panel>
        <i-cell title="时间标签列表" is-link value="管理" url="/pages/labels/main" i-class="my-cell">
        </i-cell>
      </i-panel>
      <i-panel>
        <div class="my-padding">
          <i-tag
            i-class="my-tag"
            v-for="item in tags"
            :key="index"
            :checkable="true"
            :name="index"
            :color="item.color"
            :checked="item.checked"
            type="border"
            @change="tagChange"
            style="margin-right:5px;">
            {{item.name}}
          </i-tag>
        </div>
      </i-panel>


      <i-panel>
        <i-col span="16" i-class="my-avatar-class">
          <i-avatar v-if="show_avatar" :src="avatar_url" size="large" shape="shape"></i-avatar>
          当前标签
        </i-col>
          <view class="my-center-class">
            <div class="my-circle-class">
              <span style="display: flex;justify-content:center;align-items:Center;height: 100%;color: white;">{{run_time}}</span>
            </div>
          </view>
          <span style="color: #2d8cf0;width:100%;display: flex;justify-content:center;text-align: justify;margin-bottom: 1rem;font-size: 20px;">{{run_tags}}</span>
      </i-panel>
    </div>

    <div v-show="show_time_tree">
      <i-panel>
        <i-cell title="今日记录" is-link value="时间统计" url="/pages/chart/main" i-class="my-cell"></i-cell>
      </i-panel>
      <i-steps :current="vertical_current" direction="vertical" i-class="my-steps">
        <i-step>
          <div slot="title">
            {{now_tree_title}}
          </div>
          <div slot="content">
            进行中({{now_tree_time}})
          </div>
        </i-step>
        <i-step v-for="tree in trees">
          <div slot="title">
            {{tree.title}}
          </div>
          <div slot="content">
            {{tree.info}}
          </div>
        </i-step>
      </i-steps>
    </div>

    <i-tab-bar :current="current" @change="handleChange" fixed="true">
      <i-tab-bar-item key="label" icon="brush" current-icon="brush_fill" title="记录"></i-tab-bar-item>
      <i-tab-bar-item key="24_hour" icon="clock" current-icon="clock_fill" title="24小时"></i-tab-bar-item>
    </i-tab-bar>
  </div>
</template>

<script>
// Use Vuex
import { getToken, setToken, formatSeconds} from '@/utils/index';
import { getBaseUrl } from '@/config/config';
import store from './store';
import BS from 'js-base64';

export default {
  data () {
    return {
      //倒计时相关
      'tags': [
        // {'name': '标签4️', 'checked': false, 'color': 'green'}
        ],
      show_avatar:false,
      avatar_url:'',
      run_tags:'',
      run_time:'0秒',
      run_timestamp:0,

      //tabar
      current: 'label',
      show_tags: true,
      show_time_tree: false,
      show_now_key:'',

      //时间树相关
      vertical_current: 0,
      now_tree_title:'无',
      now_tree_time:'',
      trees:[
        // {"title":"title4","info":"已结束"}
      ]
    }
  },
  computed: {
    count () {
      return store.state.count
    }
  },
  onLoad() {
    let _self = this;
    // 查看是否授权
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success(res) {
              console.log(res.userInfo);
              _self.show_avatar = true;
              _self.avatar_url = res.userInfo.avatarUrl;
            }
          })
        }
      }
    })
  },
  onReady(){
    let _self = this;
    setInterval(function() {
      if(_self.run_tags.length !== 0){
        _self.run_timestamp ++;
        _self.runTimeChange(_self.run_timestamp);
      }else{
        _self.run_time = "请选择标签进行计时";
      }
    },1000);
    //
    // wx.getSetting({
    //   success(res) {
    //     if (!res.authSetting['scope.userInfo']) {
    //       wx.authorize({
    //         scope: 'scope.userInfo',
    //         success() {
    //           // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
    //           wx.startRecord()
    //         }
    //       })
    //     }
    //   }
    // })
  },
  onShow(){
    let _self = this;
    if(getToken().length === 0){
      wx.login({
        //获取code
        success: function (res) {
          var code = res.code; //返回code
          console.log("wx.login code", code);
          wx.request({
            url: getBaseUrl()+'/users/get_token_by_code',
            method:'POST',
            data: {
              code:code
            },
            success: function (res) {
              var token = res.data.token; //返回openid
              console.log("onShow wx.login token:",token);
              setToken(token);
              _self.getUserLabel();
            }
          })
        }
      });
    }else{
      _self.getUserLabel();
    }
  },
  methods: {
    setData (data){
      Object.keys(data).forEach(key => {
        this[key] = data[key];
      });
    },
    runLabelChange(name){
      this.run_tags=name;
    },
    runTimeChange(time){
      this.run_timestamp = time;
      this.run_time = formatSeconds(parseInt(time));
    },
    tagChange ({mp:{detail}}) {
      let _index = parseInt(detail['name']);
      this.setRunLabel(_index);
    },
    handleChange ({mp:{detail}}) {
      if(this.show_now_key === detail.key){
        return;
      }
      this.show_now_key = detail.key;
      this.show_tags = !this.show_tags;
      this.show_time_tree = !this.show_time_tree;

      // console.log("handleChange 1",this.show_tags,this.show_time_tree);
      this.setData({
        current: detail.key
      });
      if(detail.key === '24_hour'){
        this.get24TimeRecord();
      }
    },
    setRunLabel(index){
      let _self = this;
      //避免重复提交
      for(let i = 0 ; i < _self.tags.length; i ++){
        if(_self.tags[i].checked === true && i === index){
          return;
        }
      }
      this.$http.post('/label/set_run_label',
        {
          label_name:_self.tags[index].name
        },
        {
          headers:{
            Authorization: getToken()
          }
        })
        .then(function(response){
          let _new_timestamp = response.data.choose_time || 0;
          //网络请求成功后改变ui
          //UI变化
          _self.tags.forEach(function(item) {
            item.checked = false;
          });
          _self.tags[index].checked=true;
          //当前标签变化
          _self.runLabelChange(_self.tags[index].name);
          _self.runTimeChange((new Date()).getTime()/1000 - _new_timestamp);
        })
        .catch(function(response){
          console.log(response);
        });
    },
    get24TimeRecord(){
      let _self = this;
      //登录获取token
      return this.$http.post('/label/get_24_time_record',{},{
        headers:{
          Authorization: getToken()
        }
      })
        .then(function(response){
          console.log(response);
          let _data = response.data.labels;
          if(_data.length && _data.length === 0) return;
          _self.trees = [];
          for(let i = 1 ; i < _data.length; i ++){
            let _item = {};
            _item['title'] = _data[i].label_name;
            _item['info'] = _data[i].time_string;
            _self.trees.push(_item);
          }
          _self.now_tree_title = _data[0].label_name;
          _self.now_tree_time = _data[0].time_string;
        })
        .catch(function(response){
          console.log(response);
        });
    },
    // getUserToken(){
    //   //登录获取token
    //   let _Authorization = "Basic " + BS.Base64.encode("1" + ":" + "o1O_B0k7Pmy6U37XKg8XXsS9ocbE");
    //   return this.$http.post('/users/login',{},{
    //       headers:{
    //         Authorization: _Authorization
    //       }
    //     })
    //     .then(function(response){
    //       setToken(response.data.token);
    //     })
    //     .catch(function(response){
    //       console.log(response);
    //     });
    // },
    getUserLabel(){
      // console.log("getUserLabel",getToken());
      let _self = this;
      //获取标签列表
      this.$http.post('/label/get_labels',{},{
          headers:{
            Authorization: getToken()
          }
        })
        .then(function(response){
          console.log("get_labels response",response.data.data);
          let _data = response.data.data;
          _self.tags = [];
          for(let i = 0 ; i < _data.length; i ++){
            let _item = _data[i];
            let _new_tag = {};
            _new_tag['name'] = _item['label_name'];
            _new_tag['checked'] = _item['checked'];
            _new_tag['color'] = 'blue';
            if(_new_tag['checked'] === true){
              _new_tag['color'] = 'blue';
              _self.runLabelChange(_new_tag['name']);
              _self.runTimeChange((new Date()).getTime()/1000 - _item['choose_time']);
            }
            _self.tags.push(_new_tag);
          }
        })
        .catch(function(response){
          console.log(response);
        });
    }
  }
}
</script>

<style>
    .my-padding{
      padding:10px;
    }
    .my-cell{
      color:#2d8cf0;
    }
    .my-steps{
      margin-top: 0.5rem;
      margin-left: 0.5rem;
    }
    .my-avatar-class {
      margin-top: 10px;
      margin-left: 10px;
    }
    .my-center-class {
        /*flex 布局*/
        display: flex;
        /*实现垂直居中*/
        align-items: center;
        /*实现水平居中*/
        justify-content: center;
        text-align: justify;

        /*大小*/
        width: 100%;
        height: 5rem;

    }
    .my-circle-class{
        background: #2d8cf0;
        border-radius:80%;
        width: 4rem;
        height: 4rem;
    }
    .my-tag{
      font-size: 16px;
    }

</style>
